const express = require('express');
const githubTrendingCrawler = require('./crawlers/githubTrendingCrawler');
const fs = require('fs');
const path = require('path');
const os = require('os');
const app = express();
const port = 3000;

// 获取本地IP地址
function getLocalIP() {
  const interfaces = os.networkInterfaces();
  for (const devName in interfaces) {
    const iface = interfaces[devName];
    for (const alias of iface) {
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
        return alias.address;
      }
    }
  }
  return '127.0.0.1';
}

const localIP = getLocalIP();

// 提供静态文件服务，使 public 目录下的文件可以被访问
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', (req, res) => {
  res.send('Hello World!');
});
app.get('/api/trending', async (req, res) => {
  try {
    // 获取查询参数，默认为daily
    const { period = 'daily' } = req.query;
    const validPeriods = ['daily', 'weekly', 'monthly'];
    
    // 验证period参数
    if (!validPeriods.includes(period)) {
      return res.status(400).json({
        error: 'Invalid period parameter',
        validOptions: validPeriods
      });
    }
    
    // 构建数据目录路径
    const dataDir = path.join(__dirname, 'data');
    
    // 构建文件匹配模式
    const filePattern = `github-trending-${period}-*.json`;
    
    try {
      // 读取data目录中的所有文件
      const files = fs.readdirSync(dataDir);
      
      // 筛选出匹配当前period的文件
      const matchingFiles = files.filter(file => 
        file.startsWith(`github-trending-${period}-`) && file.endsWith('.json')
      );
      
      if (matchingFiles.length === 0) {
        return res.status(404).json({
          error: `No trending ${period} data available`,
          period: period
        });
      }
      
      // 按文件名排序（日期在文件名中，最新的排在前面）
      matchingFiles.sort((a, b) => {
        const dateA = a.match(/-(\d{4}-\d{2}-\d{2})\.json$/)[1];
        const dateB = b.match(/-(\d{4}-\d{2}-\d{2})\.json$/)[1];
        return new Date(dateB) - new Date(dateA);
      });
      
      // 读取最新的文件
      const latestFile = matchingFiles[0];
      const filePath = path.join(dataDir, latestFile);
      
      // 提取日期信息
      const dateMatch = latestFile.match(/-(\d{4}-\d{2}-\d{2})\.json$/);
      const fileDate = dateMatch ? dateMatch[1] : 'unknown';
      
      const data = fs.readFileSync(filePath, 'utf8');
      return res.json({
        ...JSON.parse(data), 
        source: 'cached',
        date: fileDate
      });
      
    } catch (error) {
      if (error.code === 'ENOENT') {
        return res.status(404).json({
          error: `Data directory not found`,
          directory: dataDir
        });
      }
      throw error;
    }
  } catch (error) {
    console.error('请求处理失败:', error);
    res.status(500).json({
      error: 'Server error',
      details: error.message
    });
  }
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
  console.log(`Server running at http://${localIP}:${port}`);
});